<template>
  <div>
    <el-button type="primary" size="small" @click="addDialogVisible = true">添加</el-button>

    <el-table :data="deptsList" row-key="id" default-expand-all>
      <el-table-column label="名称" prop="label"></el-table-column>
      <el-table-column label="排序" prop="sort"></el-table-column>
      <el-table-column label="上级" prop="pid"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" size="small"
            @click="addDialogVisible = true; addForm.pid = row.id">添加</el-button>
          <el-button v-if="row.children.length === 0" type="danger" size="small"
            @click="deleteDept(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="添加" v-model="addDialogVisible">
      <el-form label-position="top" :model="addForm">
        <el-form-item label="菜单名称">
          <el-input v-model="addForm.label"></el-input>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="addForm.sort"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="saveAddDept">保存</el-button>
          <el-button size="small" @click="addDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>


    </el-dialog>

  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { getDeptsListApi, addDeptApi, deleteDeptByIdApi } from '@/api/depts';
import { ElMessageBox } from 'element-plus';

const addDialogVisible = ref(false);
const deptsList = ref([]);
const addForm = reactive({
  pid: '',
  label: '',
  sort: 0
});


function treeList(data = [], pid = '', res = []) {
  data.forEach(el => {
    if (el.pid === pid) {
      res.push(el);
      el.children = [];
      treeList(data, el.id, el.children);
    }
  })
  return res;
}
async function getDeptsList() {
  try {
    const res = await getDeptsListApi();
    deptsList.value = treeList(res);
  } catch (error) {
    //
  }
}

getDeptsList();

async function saveAddDept() {

  const data = {
    pid: addForm.pid,
    sort: addForm.sort,
    label: addForm.label,
  }

  try {
    await addDeptApi(data);
    addDialogVisible.value = false;
    getDeptsList();
  } catch (error) {
    //
  }
}

async function deleteDept(id) {
  try {
    await ElMessageBox.confirm('确定删除吗？', '删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await deleteDeptByIdApi(id);
    getDeptsList();
  } catch (error) {
    //...
  }
}
</script>

<style></style>